package com.myrpc.transfer.transport.socket;

import com.myrpc.handler.RpcRequestHandler;
import com.myrpc.transfer.dto.RpcRequest;
import com.myrpc.transfer.dto.RpcResponse;
import com.myrpc.util.BeanUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

@Slf4j
public class SocketRpcRequestHandlerRunnable implements Runnable{
    private Socket socket;

    public SocketRpcRequestHandlerRunnable(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        log.info("Socket server handle task by thread {}", Thread.currentThread().getName());
        RpcRequestHandler handler = BeanUtil.getBeanByType(RpcRequestHandler.class);
        try(
                ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                ) {
            //读取传输过来的请求
            RpcRequest rpcRequest = (RpcRequest) objectInputStream.readObject();
            //执行请求
            Object result = handler.handle(rpcRequest);
            //传回请求结果
            RpcResponse<Object> response = RpcResponse.success(result, rpcRequest.getRequestId());
            objectOutputStream.writeObject(response);
            objectOutputStream.flush();
        } catch (IOException | ClassNotFoundException e) {
            log.error("在执行调用时出现异常",e);
            throw new RuntimeException(e);
        }

    }
}
